/*
 * @Author: 晴鸢. 3013433857@qq.com
 * @Date: 2025-10-15 16:48:29
 * @LastEditors: 晴鸢. 3013433857@qq.com
 * @LastEditTime: 2025-10-30 23:03:31
 * @FilePath: /Learn/tcp/TcpClient.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
#include <unistd.h>
#include <cstring>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
void Usage(std::string proc)
{
    std::cout << "\nUsage:" << proc << " serverip serverport\n"
              << std::endl;
}

// 作为客户端，需要知道连接服务端的端口号和ip地址
//./tcpserver 8080 192.168.232.200
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    std::string serverip = argv[2];
    uint16_t serverport = std::stoi(argv[1]);
    // 无需显示bind，由系统自己bind
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_pton(AF_INET, serverip.c_str(), &(server.sin_addr));
    // 一次请求提供一个服务
    while (true)
    {
        int cnt = 5; // 重连次数
        bool isconnect = false;
        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            std::cerr << "sockfd create error" << std::endl;
            return 1;
        }
        do // 断线重连操作
        {  // 客户端发起connect的时候会自动进行bind
            int n = connect(sockfd, (sockaddr *)&server, sizeof(server));
            if (n < 0)
            {
                isconnect = true;
                std::cerr << "connect error...,reconnect " << cnt-- << std::endl;
                sleep(1);
            }
            else
            {
                isconnect = false;
                cnt = 5;
                break;
            }
        } while (cnt && isconnect);
        if (cnt == 0)
        {
            std::cerr << "user online off..." << std::endl;
            break;
        }
        //由客户端决定何时退出
        while (true)
        {
            std::string message;
            std::cout << "Please cin:";
            getline(std::cin, message);
            int n = write(sockfd, message.c_str(), message.size());
            if (n < 0)
            {
                std::cerr << "write error..." << std::endl;
                break;
            }
            char buffer[4096];
            int m = read(sockfd, buffer, sizeof(buffer));
            if (m > 0)
            {
                buffer[m] = 0;
                std::cout << buffer << std::endl;
            }
            else
                break;
        }
        close(sockfd);
    }
    return 0;
}